import os
import re
import requests

def download_fonts(css_path, target_dir):
    """
    从指定 css 文件中解析所有 .woff2 地址，并下载到 target_dir/fonts/
    """
    fonts_dir = os.path.join(target_dir, "fonts")
    os.makedirs(fonts_dir, exist_ok=True)

    with open(css_path, "r", encoding="utf-8") as f:
        css_content = f.read()

    # 匹配 url(...) 中的 .woff2 链接
    pattern = re.compile(r"url\((https?://[^)]+?\.woff2)\)")
    urls = pattern.findall(css_content)

    if not urls:
        print(f"[WARN] 未在 {css_path} 中找到任何 .woff2 链接")
        return

    print(f"共找到 {len(urls)} 个字体文件待处理 ({css_path})")

    for i, url in enumerate(urls, 1):
        filename = os.path.basename(url.split("?")[0])
        filepath = os.path.join(fonts_dir, filename)

        if os.path.exists(filepath):
            print(f"[{i}/{len(urls)}] 已存在，跳过：{filename}")
            continue

        print(f"[{i}/{len(urls)}] 正在下载：{filename}")
        try:
            resp = requests.get(url, timeout=20)
            resp.raise_for_status()
            with open(filepath, "wb") as f:
                f.write(resp.content)
            print(f"    ✅ 下载完成：{filename}")
        except Exception as e:
            print(f"    ❌ 下载失败：{filename} ({e})")

if __name__ == "__main__":
    tasks = [
        ("Open+Sans/fonts-open-sans.css", "Open+Sans"),
        ("Roboto/fonts-roboto.css", "Roboto"),
    ]

    for css_path, target_dir in tasks:
        if not os.path.exists(css_path):
            print(f"[ERROR] 文件不存在：{css_path}")
            continue
        download_fonts(css_path, target_dir)
